import { createRouter, createWebHistory } from 'vue-router'
import AdminLayout from '../components/layout/AdminLayout.vue'
import ClientLayout from '../components/layout/ClientLayout.vue'
import { isLoggedIn, refreshTokenExpire, setToken } from '../utils/auth'
import { ElMessage } from 'element-plus'

// 管理端路由
export const constantRoutes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/login/index.vue'),
    meta: { title: '登录', hidden: true, noAuth: true },
  },
  {
    path: '/admin/login',
    name: 'AdminLogin',
    component: () => import('../views/login/index.vue'),
    meta: { title: '管理员登录', hidden: true, noAuth: true },
  },
  {
    path: '/admin/404',
    component: () => import('../views/error/404.vue'),
    meta: { title: '404', hidden: true, noAuth: true },
  },
  {
    path: '/admin',
    component: AdminLayout,
    redirect: '/admin/dashboard',
    meta: { title: '首页', icon: 'HomeFilled', hidden: false },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('../views/dashboard/index.vue'),
        meta: {
          title: '首页',
          icon: 'HomeFilled',
          affix: true,
          keepAlive: true // 缓存首页
        },
      },
    ],
  },
  // 用户管理
  {
    path: '/admin/user',
    component: AdminLayout,
    redirect: '/admin/user/list',
    meta: { title: '用户管理', icon: 'User' },
    children: [
      {
        path: 'list',
        name: 'UserList',
        component: () => import('../views/system/user/index.vue'),
        meta: {
          title: '用户列表',
          icon: 'UserFilled',
          keepAlive: true // 缓存用户列表
        },
      },
      {
        path: 'role',
        name: 'RoleList',
        component: () => import('../views/system/role/index.vue'),
        meta: {
          title: '角色管理',
          icon: 'Avatar',
          keepAlive: true // 缓存角色管理
        },
      },
    ],
  },
  // 系统管理
  {
    path: '/admin/system',
    component: AdminLayout,
    redirect: '/admin/system/config',
    meta: { title: '系统管理', icon: 'Setting' },
    children: [
      {
        path: 'config',
        name: 'Config',
        component: () => import('../views/system/config/index.vue'),
        meta: {
          title: '系统配置',
          icon: 'Tools',
          keepAlive: true // 缓存系统配置
        },
      },
      {
        path: 'log',
        name: 'Log',
        component: () => import('../views/system/log/index.vue'),
        meta: {
          title: '操作日志',
          icon: 'List',
          keepAlive: false // 日志页面不缓存，保证数据实时性
        },
      },
    ],
  },
  // 数据管理
  {
    path: '/admin/data',
    component: AdminLayout,
    redirect: '/admin/data/source',
    meta: { title: '数据管理', icon: 'DataAnalysis' },
    children: [
      {
        path: 'source',
        name: 'dataSource',
        component: () => import('../views/data/source/index.vue'),
        meta: {
          title: '数据源管理',
          icon: 'Connection',
          keepAlive: true // 缓存数据源管理
        },
      },
      {
        path: 'dataset',
        name: 'dataDataset',
        component: () => import('../views/data/dataset/index.vue'),
        meta: {
          title: '数据集管理',
          icon: 'Grid',
          keepAlive: true // 缓存数据集管理
        },
      },
      {
        path: 'field/:datasetId',
        name: 'dataField',
        component: () => import('../views/data/field/index.vue'),
        meta: {
          title: '字段管理',
          icon: 'List',
          hidden: true,
          keepAlive: false // 字段管理页面需要根据参数重新加载
        },
      },
      // {
      //   path: 'api',
      //   name: 'ExternalApi',
      //   component: () => import('../views/data/api/index.vue'),
      //   meta: { title: '外部API管理', icon: 'Link' },
      // },
    ],
  },
  // 知识库管理
  {
    path: '/admin/knowledge',
    component: AdminLayout,
    redirect: '/admin/knowledge/bases',
    meta: { title: '知识库管理', icon: 'Collection' },
    children: [
      {
        path: 'bases',
        name: 'KnowledgeBases',
        component: () => import('../views/knowledge/bases.vue'),
        meta: {
          title: '知识库',
          icon: 'Folder',
          keepAlive: true // 缓存知识库列表
        },
      },
      {
        path: 'items',
        name: 'KnowledgeItems',
        component: () => import('../views/knowledge/items.vue'),
        meta: {
          title: '知识条目',
          icon: 'Document',
          keepAlive: true // 缓存知识条目
        },
      },
      {
        path: 'content-edit/:itemId',
        name: 'KnowledgeContentEdit',
        component: () => import('../views/knowledge/content-edit.vue'),
        meta: {
          title: '内容编辑',
          icon: 'Edit',
          activeMenu: '/admin/knowledge/items',
          hidden: true,
          keepAlive: false // 编辑页面不缓存，避免数据混乱
        },
      },
    ],
  },
  // 查询记录管理
  {
    path: '/admin/records',
    component: AdminLayout,
    redirect: '/admin/records/index',
    meta: { title: '会话管理', icon: 'ChatDotRound' },
    children: [
      {
        path: 'index',
        name: 'RecordsList',
        component: () => import('../views/records/index.vue'),
        meta: {
          title: '会话记录',
          icon: 'ChatLineRound',
          keepAlive: true // 缓存会话记录列表
        },
      },
      {
        path: 'detail/:id',
        name: 'RecordDetail',
        component: () => import('../views/records/detail.vue'),
        meta: {
          title: '会话详情',
          icon: 'Document',
          activeMenu: '/admin/records/index',
          hidden: true,
          keepAlive: false // 详情页面不缓存
        },
      },
      {
        path: 'analytics',
        name: 'RecordsAnalytics',
        component: () => import('../views/records/analytics.vue'),
        meta: {
          title: '查询分析',
          icon: 'DataAnalysis',
          keepAlive: true // 缓存分析页面，但需要手动刷新数据
        },
      },
      {
        path: 'model-logs',
        name: 'ModelLogs',
        component: () => import('../views/system/model-logs/index.vue'),
        meta: {
          title: '模型调用记录',
          icon: 'Histogram',
          keepAlive: false // 模型日志不缓存，保证数据实时性
        },
      },
    ],
  },
  // 404页面应该放在最后
  { path: '/admin/:pathMatch(.*)*', redirect: '/admin/404', meta: { hidden: true, noAuth: true } },

  // 独立的知识库内容编辑页面 - 全屏显示，不使用框架布局
  {
    path: '/knowledge-edit/:itemId',
    name: 'KnowledgeContentEditFullscreen',
    component: () => import('../views/knowledge/content-edit.vue'),
    meta: {
      title: '知识库内容编辑',
      noAuth: false,
      hidden: true
    }
  },
]

// 客户端路由
export const clientRoutes = [
  // 独立聊天窗口路由 - 用于系统集成，通过URL token验证
  {
    path: '/embed-chat',
    name: 'EmbedChat',
    component: () => import('../client/views/EmbedChatView.vue'),
    meta: { title: '聊天窗口', noAuth: true },
  },
  // 客户端首页 - 作为默认路由，但需要登录验证
  {
    path: '/',
    component: ClientLayout,
    meta: { title: '析语AI数据分析', requiresAuth: true },
    children: [
      {
        path: '',
        name: 'ClientHome',
        component: () => import('../client/app.vue'),
        meta: { title: '析语AI数据分析平台', requiresAuth: true },
      },
      {
        path: 'chat',
        name: 'Chat',
        component: () => import('../client/app.vue'),
        meta: { title: '会话分析', requiresAuth: true },
        redirect: '/chat/chat',
        children: [
          {
            path: 'chat',
            name: 'ChatV2Chat',
            component: () => import('../client/app.vue'),
            meta: { title: '会话分析', requiresAuth: true, activeMenu: 'chat' },
          },
          {
            path: 'dataset',
            name: 'ChatV2Dataset',
            component: () => import('../client/app.vue'),
            meta: { title: '数据集管理', requiresAuth: true, activeMenu: 'dataset' },
          },
          {
            path: 'dataset/:id',
            name: 'ChatV2DatasetDetail',
            component: () => import('../client/app.vue'),
            meta: { title: '数据集详情', requiresAuth: true, activeMenu: 'dataset' },
          },
          {
            path: 'report',
            name: 'ChatV2Report',
            component: () => import('../client/app.vue'),
            meta: { title: '分析报告', requiresAuth: true, activeMenu: 'report' },
          },
          {
            path: 'knowledge',
            name: 'ChatV2Knowledge',
            component: () => import('../client/app.vue'),
            meta: { title: '知识库', requiresAuth: true, activeMenu: 'knowledge' },
          },
          {
            path: 'knowledge/:id',
            name: 'ChatV2KnowledgeDetail',
            component: () => import('../client/app.vue'),
            meta: { title: '知识库详情', requiresAuth: true, activeMenu: 'knowledge' },
          },
        ],
      },
      {
        path: 'report/:reportId',
        name: 'report-edit',
        component: () => import('../client/views/ReportEditView.vue'),
        meta: { title: '分析报告编辑', requiresAuth: true },
      },
    ],
  },
  // 通用404重定向
  { path: '/:pathMatch(.*)*', redirect: '/admin/404', meta: { hidden: true, noAuth: true } },
]

// 组合所有路由
const allRoutes = [...clientRoutes, ...constantRoutes]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: allRoutes,
  scrollBehavior: () => ({ top: 0 }),
})

// 设置白名单，不需要验证登录的路径（只包含登录和404页面）
const whiteList = ['/login', '/admin/login', '/admin/404']

// 全局前置守卫 - 验证用户是否登录
router.beforeEach(async (to, from, next) => {
  // 如果前往不需要认证的页面，直接放行
  if (whiteList.includes(to.path) || to.meta.noAuth) {
    next()
    return
  }

    // 检查URL中是否有token参数，如果有则直接使用该token进行认证
  if (to.query.token) {
    // 从URL中获取token并存储到localStorage
    const urlToken = to.query.token
    setToken(urlToken)

    // 获取用户信息并存储
    try {
      // 动态导入用户store和API
      const { useUserStore } = await import('@/stores/user')
      const { getUserInfo } = await import('@/api/user')
      const { setUserInfo } = await import('@/utils/auth')

      const userStore = useUserStore()

      // 获取用户信息
      const userInfoData = await getUserInfo()

      // 存储用户信息到localStorage和store
      setUserInfo(userInfoData)
      userStore.setUserInfo(userInfoData)

      console.log('URL token登录成功，用户信息已缓存:', userInfoData)
    } catch (error) {
      console.error('URL token登录时获取用户信息失败:', error)
      // 如果获取用户信息失败，清除token并跳转到登录页
      const { clearAuth } = await import('@/utils/auth')
      clearAuth()
      ElMessage.error('登录验证失败，请重新登录')
      const isAdminPath = to.path.includes('/admin/')
      const loginPath = isAdminPath ? '/admin/login' : '/login'
      next(loginPath)
      return
    }

    // 清除URL中的token参数，避免在浏览器地址栏中暴露
    const newQuery = { ...to.query }
    delete newQuery.token

    // 重定向到不包含token的同一路径
    next({
      path: to.path,
      query: newQuery,
      params: to.params,
      replace: true
    })
    return
  }

  // 验证用户是否已登录 - 所有需要认证的路由统一处理
  if (isLoggedIn()) {
    // 刷新token过期时间
    refreshTokenExpire()

    // 如果是从登录页重定向过来的，获取原始请求的URL
    if ((from.path === '/login' || from.path === '/admin/login') && to.query.redirect) {
      const redirectPath = decodeURIComponent(to.query.redirect)
      next(redirectPath)
    } else {
      next()
    }
  } else {
    // 未登录，根据目标路径决定重定向到哪个登录页
    ElMessage.warning('请先登录')

    // 检查是否访问的是管理端路径
    const isAdminPath = to.path.includes('/admin/')
    const loginPath = isAdminPath ? '/admin/login' : '/login'

    next(`${loginPath}?redirect=${encodeURIComponent(to.fullPath)}`)
  }
})

// 全局后置钩子 - 设置页面标题和处理客户端样式
router.afterEach((to) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 析语AI数据分析平台` : '析语AI数据分析平台'

  // 动态管理客户端样式 - 只在非管理端路由加载
  const isAdminRoute = to.path.includes('/admin/')
  const clientStyleLink = document.querySelector('link[href="/src/client/style.css"]')

  if (!isAdminRoute && !clientStyleLink) {
    const link = document.createElement('link')
    link.rel = 'stylesheet'
    link.type = 'text/css'
    link.href = '/src/client/style.css'
    document.head.appendChild(link)
  } else if (isAdminRoute && clientStyleLink) {
    // 如果是管理端路由但样式已加载，则移除样式
    clientStyleLink.remove()
  }
})

export default router
